package framework.jackson;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.apache.commons.lang3.StringEscapeUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

/**
 * 设置 @JsonProperty 后，序列化反序列化都只识别指定的属性名
 *
 * @author ME
 * @date 2021/1/17
 */
public class TestJsonProperty {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper()
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"))
                .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)
                .registerModule(new SimpleModule()
                        // .addSerializer(new StdSerializer<BigDecimal>(BigDecimal.class) {
                        //     @Override
                        //     public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) throws IOException {
                        //         gen.writeString(value.toPlainString());
                        //     }
                        // })
                        .addSerializer(Long.class, ToStringSerializer.instance)
                        .addSerializer(long.class, ToStringSerializer.instance));

        System.out.println("ag 属性能反序列化：");
        String str = "{\"name\":\"ljy\",\"ag\":\"14\"}";
        System.out.println("源字符串为：" + str);
        Person person = mapper.readValue(str, Person.class);
        System.out.println(person);

        person.setMoney(new BigDecimal("0.00000005148554641076956121994511276767154838481760200726351203835429763013462401"));
        System.out.println("序列化后的属性为 ag：");
        System.out.println(mapper.writeValueAsString(person));

        // 对于带转义符的 json字符串，需要先反转义
        System.out.println("\n带转义符的json字符串反序列化：");
        str = "{\\\"name\\\":\\\"Jack\\\",\\\"ag\\\":\\\"999\\\"}";
        System.out.println("源字符串为：" + str);
        System.out.println("replace(\"\\\", \"\")：" + str.replace("\\", ""));
        System.out.println("unescapeJava：" + StringEscapeUtils.unescapeJava(str));
        System.out.println("unescapeJson：" + StringEscapeUtils.unescapeJson(str));
        person = mapper.readValue(StringEscapeUtils.unescapeJava(str), Person.class);
        System.out.println(person);
    }

}
